OPC Studio User's Guide and Reference
Examples - OPC Data Access - Subscribe to a single item

Example 1

.NET

// Hooking up events and receiving OPC item changes.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// OPC client and subscriber examples in C# on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using System.Threading;
using OpcLabs.EasyOpc.DataAccess;
using OpcLabs.EasyOpc.DataAccess.OperationModel;

namespace DocExamples.DataAccess._EasyDAClient
{
    partial class SubscribeItem
    {
        public static void Main1()
        {
            // Instantiate the client object.
            using (var client = new EasyDAClient())
            {
                var eventHandler = new EasyDAItemChangedEventHandler(client_ItemChanged);
                client.ItemChanged += eventHandler;

                Console.WriteLine("Subscribing item...");
                client.SubscribeItem("", "OPCLabs.KitServer.2", "Demo.Ramp", 200);

                Console.WriteLine("Process item change notifications for 30 seconds...");
                Thread.Sleep(30 * 1000);

                Console.WriteLine("Unsubscribing all items...");
                client.UnsubscribeAllItems();

                client.ItemChanged -= eventHandler;
            }

            Console.WriteLine("Finished.");
        }

        static void client_ItemChanged(object sender, EasyDAItemChangedEventArgs e)
        {
            if (e.Succeeded)
                Console.WriteLine(e.Vtq);
            else
                Console.WriteLine($"*** Failure: {e.ErrorMessageBrief}");
        }
    }
}
# Hooking up events and receiving OPC item changes.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in PowerShell on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-PowerShell .
# Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
# a commercial license in order to use Online Forums, and we reply to every post.

#requires -Version 5.1
using namespace OpcLabs.EasyOpc.DataAccess

# The path below assumes that the current directory is [ProductDir]/Examples-NET/PowerShell/Windows .
Add-Type -Path "../../../Components/Opclabs.QuickOpc/net472/OpcLabs.EasyOpcClassicCore.dll"
Add-Type -Path "../../../Components/Opclabs.QuickOpc/net472/OpcLabs.EasyOpcClassic.dll"
Add-Type -Path "../../../Components/Opclabs.QuickOpc/net472/OpcLabs.EasyOpcClassicComponents.dll"

# Instantiate the client object.
$client = New-Object EasyDAClient

# Item changed event handler
Register-ObjectEvent -InputObject $client -EventName ItemChanged -Action { 
    if ($EventArgs.Succeeded) {
        Write-Host $EventArgs.Vtq
    }
    else {
        Write-Host "*** Failure: $($EventArgs.ErrorMessageBrief)"
    }
}

Write-Host "Subscribing item..."
[IEasyDAClientExtension]::SubscribeItem($client, "", "OPCLabs.KitServer.2", "Demo.Ramp", 200)

Write-Host "Processing item changes for 30 seconds..."
$stopwatch =  [System.Diagnostics.Stopwatch]::StartNew() 
while ($stopwatch.Elapsed.TotalSeconds -lt 30) {    
    Start-Sleep -Seconds 1
}

Write-Host "Unsubscribing items..."
$client.UnsubscribeAllItems()

Write-Host "Finished."
' Hooking up events and receiving OPC item changes.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
' OPC client and subscriber examples in VB.NET on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-VBNET .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports System.Threading
Imports OpcLabs.EasyOpc.DataAccess
Imports OpcLabs.EasyOpc.DataAccess.OperationModel

Namespace DataAccess._EasyDAClient
    Partial Friend Class SubscribeItem
        Shared Sub Main1()
            Using client = New EasyDAClient()
                Dim eventHandler = New EasyDAItemChangedEventHandler(AddressOf client_ItemChanged)
                AddHandler client.ItemChanged, eventHandler

                Console.WriteLine("Subscribing item...")
                client.SubscribeItem("", "OPCLabs.KitServer.2", "Demo.Ramp", 200)
                Thread.Sleep(30 * 1000)
                client.UnsubscribeAllItems()
                RemoveHandler client.ItemChanged, eventHandler
            End Using
        End Sub

        Private Shared Sub client_ItemChanged(sender As Object, e As EasyDAItemChangedEventArgs)
            If e.Succeeded Then
                Console.WriteLine(e.Vtq)
            Else
                Console.WriteLine("*** Failure: {0}", e.ErrorMessageBrief)
            End If
        End Sub
    End Class
End Namespace

COM

// This example shows how to subscribe to changes of a single item and display the value of the item with each change.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// OPC client and subscriber examples in Object Pascal (Delphi) on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-OP .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

type
  TSubscribeItem_ClientEventHandlers = class
    // Item changed event handler
    procedure OnItemChanged(
      ASender: TObject;
      sender: OleVariant;
      const eventArgs: _EasyDAItemChangedEventArgs);
  end;

procedure TSubscribeItem_ClientEventHandlers.OnItemChanged(
  ASender: TObject;
  sender: OleVariant;
  const eventArgs: _EasyDAItemChangedEventArgs);
begin
  if eventArgs.Succeeded then
    WriteLn(eventArgs.Vtq.ToString)
  else
    WriteLn(Format('*** Failure: %s', [eventArgs.ErrorMessageBrief]));
end;

class procedure SubscribeItem.Main;
var
  Client: TEasyDAClient;
  ClientEventHandlers: TSubscribeItem_ClientEventHandlers;
begin
  // Instantiate the client object and hook events
  Client := TEasyDAClient.Create(nil);
  ClientEventHandlers := TSubscribeItem_ClientEventHandlers.Create;
  Client.OnItemChanged := ClientEventHandlers.OnItemChanged;

  Client.SubscribeItem('', 'OPCLabs.KitServer.2', 'Simulation.Random', 1000);

  WriteLn('Processing item changed events for 1 minute...');
  PumpSleep(60*1000);

  WriteLn('Unsubscribing...');
  Client.UnsubscribeAllItems;

  WriteLn('Waiting for 5 seconds...');
  PumpSleep(5*1000);

  WriteLn('Finished.');
  FreeAndNil(Client);
  FreeAndNil(ClientEventHandlers);
end;
// This example shows how to subscribe to changes of a single item and display the value of the item with each change.
//
// Some related documentation: http://php.net/manual/en/function.com-event-sink.php . Pay attention to the comment that says 
// "Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make 
// sense to run it in a web server context.". What they are trying to say is that processing a web request should be 
// a short-lived code, which does not fit well with the idea of being subscribed to events and received them over longer time. 
// It is possible to write such code, but it is only useful when processing the request is allowed to take relatively long. Or, 
// when you are using PHP from command-line, or otherwise - not to serve a web page directly.
// 
// Subscribing to QuickOPC-COM events in the context of PHP Web application, while not imposing the limitations to the request 
// processing time, has to be "worked around", e.g. using the "event pull" mechanism.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// OPC client and subscriber examples in PHP on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-PHP .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

class DEasyDAClientEvents {
    function ItemChanged($varSender, $varE)
    {
        if ($varE->Succeeded)
        {
        print $varE->Vtq->ToString();
            print "\n";
        }
        else
        {
            printf("*** Failure: %s\n", $varE->ErrorMessageBrief);
        }
    }
}

$Client = new COM("OpcLabs.EasyOpc.DataAccess.EasyDAClient");
$Events = new DEasyDAClientEvents();
com_event_sink($Client, $Events, "DEasyDAClientEvents");

$Client->SubscribeItem("", "OPCLabs.KitServer.2", "Simulation.Random", 1000);

print "Processing item changed events for 1 minute...\n";
$startTime = time(); do { com_message_pump(1000); } while (time() < $startTime + 60);
REM This example shows how to subscribe to changes of a single item and display the value of the item with each change.
REM
REM Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
REM OPC client and subscriber examples in Visual Basic on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-VB .
REM Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
REM a commercial license in order to use Online Forums, and we reply to every post.

' The client object, with events
'Public WithEvents Client1 As EasyDAClient

Private Sub SubscribeItem_Main_Command_Click()
    OutputText = ""
    
    ' Instantiate the client object and hook events
    Set Client1 = New EasyDAClient

    OutputText = OutputText & "Subscribing..." & vbCrLf
    Call Client1.SubscribeItem("", "OPCLabs.KitServer.2", "Simulation.Random", 1000)

    OutputText = OutputText & "Processing item changed events for 1 minute..." & vbCrLf
    Pause 60000

    OutputText = OutputText & "Unsubscribing..." & vbCrLf
    Client1.UnsubscribeAllItems

    OutputText = OutputText & "Waiting for 5 seconds..." & vbCrLf
    Pause 5000

    OutputText = OutputText & "Finished." & vbCrLf
    Set Client1 = Nothing
End Sub

Public Sub Client1_ItemChanged(ByVal sender As Variant, ByVal eventArgs As EasyDAItemChangedEventArgs)
    If eventArgs.Succeeded Then
        OutputText = OutputText & eventArgs.vtq & vbCrLf
    Else
        OutputText = OutputText & "*** Failure: " & eventArgs.ErrorMessageBrief & vbCrLf
    End If
End Sub
Rem This example shows how to subscribe to changes of a single item and display the value of the item with each change.
Rem
Rem Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
Rem OPC client and subscriber examples in VBScript on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-VBScript .
Rem Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
Rem a commercial license in order to use Online Forums, and we reply to every post.

Option Explicit

Dim Client: Set Client = CreateObject("OpcLabs.EasyOpc.DataAccess.EasyDAClient")
WScript.ConnectObject Client, "Client_"

Client.SubscribeItem "", "OPCLabs.KitServer.2", "Simulation.Random", 1000

WScript.Echo "Processing item changed events for 1 minute..."
WScript.Sleep 60*1000



Sub Client_ItemChanged(Sender, e)
    If Not (e.Succeeded) Then
        WScript.Echo "*** Failure: " & e.ErrorMessageBrief
        Exit Sub
    End If

    WScript.Echo e.Vtq.ToString
End Sub

Python

# Hooking up events and receiving OPC item changes.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
# a commercial license in order to use Online Forums, and we reply to every post.
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc
import time

# Import .NET namespaces.
from OpcLabs.EasyOpc.DataAccess import *


# Item changed event handler.
def itemChanged(sender, e):
    if e.Succeeded:
        print(e.Vtq)
    else:
        print('*** Failure: ', e.ErrorMessageBrief, sep='')


# Instantiate the client object.
client = EasyDAClient()

client.ItemChanged += itemChanged

print('Subscribing item changes...')
IEasyDAClientExtension.SubscribeItem(client, '', 'OPCLabs.KitServer.2', 'Demo.Ramp', 200)

print('Processing item change notifications for 30 seconds...')
time.sleep(30)

print('Unsubscribing all items...')
client.UnsubscribeAllItems()

client.ItemChanged -= itemChanged

print('Finished.')

Example 2

.NET

// This example subscribes to changes of 2 items separately, and displays rich information available with each item changed
// event notification.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// OPC client and subscriber examples in C# on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using System.Diagnostics;
using System.Threading;
using OpcLabs.EasyOpc.DataAccess;
using OpcLabs.EasyOpc.DataAccess.OperationModel;

namespace DocExamples.DataAccess._EasyDAItemChangedEventArgs
{
    class General
    {
        public static void Main1()
        {
            // Instantiate the client object.
            using (var client = new EasyDAClient())
            {
                var eventHandler = new EasyDAItemChangedEventHandler(client_ItemChanged);
                client.ItemChanged += eventHandler;

                Console.WriteLine("Subscribing items...");
                client.SubscribeItem("", "OPCLabs.KitServer.2", "Simulation.Random", 5 * 1000);
                client.SubscribeItem("", "OPCLabs.KitServer.2", "Trends.Ramp (1 min)", 5 * 1000);

                Console.WriteLine("Processing item changed events for 1 minute...");
                Thread.Sleep(60 * 1000);
            }
        }

        static void client_ItemChanged(object sender, EasyDAItemChangedEventArgs e)
        {
            Console.WriteLine();
            Console.WriteLine($"e.Arguments.State: {e.Arguments.State}");
            Console.WriteLine($"e.Arguments.ServerDescriptor.MachineName: {e.Arguments.ServerDescriptor.MachineName}");
            Console.WriteLine($"e.Arguments.ServerDescriptor.ServerClass: {e.Arguments.ServerDescriptor.ServerClass}");
            Console.WriteLine($"e.Arguments.ItemDescriptor.ItemId: {e.Arguments.ItemDescriptor.ItemId}");
            Console.WriteLine($"e.Arguments.ItemDescriptor.AccessPath: {e.Arguments.ItemDescriptor.AccessPath}");
            Console.WriteLine($"e.Arguments.ItemDescriptor.RequestedDataType: {e.Arguments.ItemDescriptor.RequestedDataType}");
            Console.WriteLine($"e.Arguments.GroupParameters.Locale: {e.Arguments.GroupParameters.Locale}");
            Console.WriteLine($"e.Arguments.GroupParameters.RequestedUpdateRate: {e.Arguments.GroupParameters.RequestedUpdateRate}");
            Console.WriteLine($"e.Arguments.GroupParameters.PercentDeadband: {e.Arguments.GroupParameters.PercentDeadband}");
            if (e.Succeeded)
            {
                Debug.Assert(!(e.Vtq is null));
                Console.WriteLine($"e.Vtq.Value: {e.Vtq.Value}");
                Console.WriteLine($"e.Vtq.Timestamp: {e.Vtq.Timestamp}");
                Console.WriteLine($"e.Vtq.TimestampLocal: {e.Vtq.TimestampLocal}");
                Console.WriteLine($"e.Vtq.Quality: {e.Vtq.Quality}");
            }
            else
            {
                Debug.Assert(!(e.Exception is null));
                Console.WriteLine($"e.Exception.Message: {e.Exception.Message}");
                Console.WriteLine($"e.Exception.Source: {e.Exception.Source}");
            }
        }


        // Example output:
        //
        //Processing item changed events for 1 minute...
        //
        //e.Arguments.State: 
        //e.Arguments.ServerDescriptor.MachineName: 
        //e.Arguments.ServerDescriptor.ServerClass: OPCLabs.KitServer.2
        //e.Arguments.ItemDescriptor.ItemId: Simulation.Random
        //e.Arguments.ItemDescriptor.AccessPath: 
        //e.Arguments.ItemDescriptor.RequestedDataType: Empty
        //e.Arguments.GroupParameters.Locale: 0
        //e.Arguments.GroupParameters.RequestedUpdateRate: 5000
        //e.Arguments.GroupParameters.PercentDeadband: 0
        //e.Vtq.Value: 0.00125125888851588
        //e.Vtq.Timestamp: 4/10/2020 4:35:25 PM
        //e.Vtq.TimestampLocal: 4/10/2020 6:35:25 PM
        //e.Vtq.Quality: GoodNonspecific (192)
        //
        //e.Arguments.State: 
        //e.Arguments.ServerDescriptor.MachineName: 
        //e.Arguments.ServerDescriptor.ServerClass: OPCLabs.KitServer.2
        //e.Arguments.ItemDescriptor.ItemId: Trends.Ramp(1 min)
        //e.Arguments.ItemDescriptor.AccessPath: 
        //e.Arguments.ItemDescriptor.RequestedDataType: Empty
        //e.Arguments.GroupParameters.Locale: 0
        //e.Arguments.GroupParameters.RequestedUpdateRate: 5000
        //e.Arguments.GroupParameters.PercentDeadband: 0
        //e.Vtq.Value: 0.431881904602051
        //e.Vtq.Timestamp: 4/10/2020 4:35:25 PM
        //e.Vtq.TimestampLocal: 4/10/2020 6:35:25 PM
        //e.Vtq.Quality: GoodNonspecific (192)
        //
        //...
    }
}

COM

Rem This example subscribes to changes of 2 items separately, and displays rich information available with each item changed
Rem event notification.
Rem
Rem Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
Rem OPC client and subscriber examples in VBScript on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-VBScript .
Rem Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
Rem a commercial license in order to use Online Forums, and we reply to every post.

Option Explicit

Dim Client: Set Client = CreateObject("OpcLabs.EasyOpc.DataAccess.EasyDAClient")
WScript.ConnectObject Client, "Client_"

Client.SubscribeItem "", "OPCLabs.KitServer.2", "Simulation.Random", 5*1000
Client.SubscribeItem "", "OPCLabs.KitServer.2", "Trends.Ramp (1 min)", 5*1000

WScript.Echo "Processing item changed events for 1 minute..."
WScript.Sleep 60*1000



Sub Client_ItemChanged(Sender, e)
    On Error Resume Next
    WScript.Echo
    WScript.Echo "e.Arguments.State: " & e.Arguments.State
    WScript.Echo "e.Arguments.ServerDescriptor.MachineName: " & e.Arguments.ServerDescriptor.MachineName
    WScript.Echo "e.Arguments.ServerDescriptor.ServerClass: " & e.Arguments.ServerDescriptor.ServerClass
    WScript.Echo "e.Arguments.ItemDescriptor.ItemId: " & e.Arguments.ItemDescriptor.ItemId
    WScript.Echo "e.Arguments.ItemDescriptor.AccessPath: " & e.Arguments.ItemDescriptor.AccessPath
    WScript.Echo "e.Arguments.ItemDescriptor.RequestedDataType: " & e.Arguments.ItemDescriptor.RequestedDataType
    WScript.Echo "e.Arguments.GroupParameters.Locale: " & e.Arguments.GroupParameters.Locale
    WScript.Echo "e.Arguments.GroupParameters.RequestedUpdateRate: " & e.Arguments.GroupParameters.RequestedUpdateRate
    WScript.Echo "e.Arguments.GroupParameters.PercentDeadband: " & e.Arguments.GroupParameters.PercentDeadband
    WScript.Echo "e.Exception.Message: " & e.Exception.Message
    WScript.Echo "e.Exception.Source: " & e.Exception.Source
    WScript.Echo "e.Exception.ErrorCode: " & e.Exception.ErrorCode
    WScript.Echo "e.Vtq.Value: " & e.Vtq.Value
    WScript.Echo "e.Vtq.Timestamp: " & e.Vtq.Timestamp
    WScript.Echo "e.Vtq.TimestampLocal: " & e.Vtq.TimestampLocal
    WScript.Echo "e.Vtq.Quality: " & e.Vtq.Quality
End Sub
See Also

Concepts

Examples - Client OPC Unified Architecture

Examples - Client OPC Alarms&Events

Examples - Client OPC DA Layered Extensions

Installed Examples - Client Console